package org.liuwei.concurent04.CurrentLimit02;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

//即一个时间窗口内的请求数
//我们使用Guava的Cache来存储计数器，过期时间设置为2秒（保证1秒内的计数器是有的）
public class CurrentLimit2 {
	static LoadingCache<Long, AtomicLong> counter = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS)
			.build(new CacheLoader<Long, AtomicLong>() {
				@Override
				public AtomicLong load(Long seconds) throws Exception {
					return new AtomicLong(0);
				}
			});
	static long limit = 4;

	public static void main(String[] args) {
		Thread t1 = new Thread(new AddTask(), "t1");
		Thread t2 = new Thread(new AddTask(), "t2");
	
		t1.start();
		t2.start();
	
	}

	public static void limit() throws InterruptedException, ExecutionException {
		while (true) {
			// 得到当前秒
			TimeUnit.MILLISECONDS.sleep(50);
			long currentSeconds = System.currentTimeMillis() / 1000;
			if (counter.get(currentSeconds).incrementAndGet() > limit) {
				System.out.println("限流了:" + currentSeconds);
				continue;
			}
			exe();
			// 处理请求
		}
	}

	public static void exe() throws InterruptedException {
		TimeUnit.MILLISECONDS.sleep(100);
		System.err.println("我执行了！");
	}
}

class AddTask implements Runnable {
	public void run() {
		try {
			CurrentLimit2.limit();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
